import { router } from "@/router";
import { RouteRecordRaw } from "vue-router";
import { useUserStore } from "@/store/user";
import { useDictStore } from "@/store/dict";
import { useControlPanel } from "@/store/controlPanel";
import { start, close } from "@/util/nprogress";

import _ from "lodash";
declare global {
  interface ImportMeta {
    readonly glob: any;
  }
}
const whiteList = ["Login", "Error"];
let isMenuInited = false;
router.beforeEach(async (to: any, from: any, next: any) => {
  const {
    initMeun,
    menuList,
    clearToken,
    cleanRefreshToken,
    cleanMenu,
    clearUserInfo,
  } = useUserStore();
  const { initDictList, cleanDictList } = useDictStore();
  if (whiteList.includes(to.name)) {
    if (to.name == "Login") {
      //重置菜单数据
      cleanMenu();
      clearUserInfo();
      cleanDictList();
      isMenuInited = false; //重置菜单初始化状态
    }
    start(); //开启页面进入进度条
    next();
  } else {
    if (localStorage.getItem("token")) {
      try {
        if (menuList.length > 1 || isMenuInited) {
          //不大于1的话token刷新token失效就会没菜单了，只有默认首页哈哈
          next();
          return;
        }
        //初始化菜单
        await initMeun();
        await initDictList();
        isMenuInited = true;
        start(); //开启页面进入进度条
        next({ ...to });
      } catch (error) {
        clearToken();
        cleanRefreshToken();
        start(); //开启页面进入进度条
        isMenuInited = false; //重置菜单初始化状态
        next("/login");
      }
    } else {
      start(); //开启页面进入进度条
      isMenuInited = false; //重置菜单初始化状态
      next("/login");
    }
  }
});
router.afterEach((to: any, from: any) => {
  const { initEnteryMenuData } = useUserStore();
  initEnteryMenuData(to.fullPath);
  const { closeLoading } = useControlPanel();
  closeLoading();
  close(); //关闭页面进入进度条
});
